<!-- src/components/GlobalToast.vue -->
<script lang="ts" setup>
import { deepClone, isFunction } from 'wot-design-uni/components/common/util'
import { useMessage } from "wot-design-uni"
import { useGlobalMessage } from "@/stores";
import { getCurrentPath } from "@/utils";
const store = useGlobalMessage()
const { messageOptions, currentPage, currentKey } = storeToRefs(store)

const message = useMessage('globalMessage')
// @ts-ignore
const currentPath = getCurrentPath()

// 支付宝小程序兼容性处理
// #ifdef MP-ALIPAY
const hackAlipayVisible = ref(false)
nextTick(() => {
  hackAlipayVisible.value = true
})
// #endif

// 监听全局状态变化
watch(currentKey, () => {
  if (currentKey.value>1) {
    const options = deepClone(messageOptions.value)
    // 只在当前页面显示 Toast
    if (currentPage.value === currentPath && options) {
      message.show(options).then((res) => {
        if (isFunction(options.success)) {
          options.success(res)
        }
      }).catch((err) => {
        if (isFunction(options.fail)) {
          options.fail(err)
        }
      })
    }
  }else {
    message.close()
  }
})
</script>

<template>
  <!-- 支付宝小程序特殊处理 -->
  <!-- #ifdef MP-ALIPAY -->
  <wd-message-box v-if="hackAlipayVisible" selector="globalMessage" :closed="store.close" />
  <!-- #endif -->
  <!-- #ifndef MP-ALIPAY -->
  <wd-message-box selector="globalMessage" :closed="store.close" />
  <!-- #endif -->
</template>